const express = require('express');
const User = require('../../models/User');
const bcrypt = require('bcrypt');
//jwt使用
const jwt = require('jsonwebtoken');
//引入头像库
const gravatar = require('gravatar');
const keys = require('../../config/keys');

const passport = require('passport');


//使用路由
const router = express.Router();

/**
 * $route GET /api/users/test
 * @desc 返回请求的json数据
 * @access public
 */
// router.get("/test", (req, res) => {
//     res.json({msg: "login works"});
// });

/**
 * $route Post /api/users/register
 * @desc 注册功能
 * @access public
 */
router.post("/register", (req, res) => {
    //查询数据库中是否拥有邮箱
    User.findOne({email: req.body.email})
        .then((user) => {
            if (user) {//用户已存在
                return res.status(400).json("邮箱已被注册");
            } else {
                let avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});

                //注册
                const newUser = new User({
                    name: req.body.name,
                    email: req.body.email,
                    avatar,
                    identity: req.body.identity,
                    password: req.body.password
                });
                //密码加密 生成盐
                bcrypt.genSalt(10, function (err, salt) {
                    //加密
                    bcrypt.hash(newUser.password, salt, (err, hash) => {
                        if (err) throw  err;
                        //保存加密后的密码
                        newUser.password = hash;
                        //保存到数据库
                        newUser.save()
                            .then(user => res.json(user))
                            .catch(err => console.error(err));
                    });
                });
            }
        });
});


/**
 * $route Post /api/users/login
 * @desc 登录功能
 * @return "Token jwt passport"
 * @access public
 */
router.post('/login', (req, res) => {
    const {email, password} = req.body;
    //查询数据库
    User.findOne({email})
        .then(user => {
            //用户不存在
            if (!user) {
                // return res.status(404).json({email: "用户不存在！"});
                return res.status(404).json("用户不存在！");
            }

            //密码匹配
            bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if (isMatch) {
                        //jwt返回token
                        // jwt.sign("规则","加密名字","{过期时间}",()=>{})
                        const rule = {//设置规则
                            id: user.id,
                            name: user.name,
                            avatar: user.avatar,
                            identity: user.identity
                        };
                        //jwt签名
                        jwt.sign(rule, keys.secretOrKey, {expiresIn: 3600}, (err, token) => {
                            if (err) throw err;
                            //返回token
                            return res.json({
                                success: true,
                                token: "Bearer " + token
                            });
                        });
                    } else {//密码错误
                        return res.status(400).json("密码错误");
                    }
                });
        });
});

/**
 * $route Get /api/users/current
 * @desc 请求数据
 * @return return current User
 * @access private
 */
router.get('/current', passport.authenticate('jwt', {session: false}), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        identity: req.user.identity
    });
});


module.exports = router;
